/**
 * Copyright © 2012 Parag Patil
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * You may not use this file except in compliance with  Apache License, Version 2.0
 * You may obtain a copy of the license at
 * http://www.apache.org/licenses/LICENSE-2.0

**/
package org.jboss.logging.ext;


import org.apache.log4j.PatternLayout;
import org.apache.log4j.Priority;
import org.apache.log4j.net.SyslogAppender;
import org.apache.log4j.spi.LoggingEvent;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

public class SyslogHandler extends Handler {

    private SyslogAppender syslogAppender;
    private static final Map<java.util.logging.Level, org.apache.log4j.Level> levelMap = new HashMap<>();

    static {

        levelMap.put(Level.OFF, org.apache.log4j.Level.OFF);
        levelMap.put(Level.SEVERE, org.apache.log4j.Level.ERROR);
        levelMap.put(Level.WARNING, org.apache.log4j.Level.WARN);
        levelMap.put(Level.INFO, org.apache.log4j.Level.INFO);
        levelMap.put(Level.CONFIG, org.apache.log4j.Level.INFO);
        levelMap.put(Level.FINE, org.apache.log4j.Level.DEBUG);
        levelMap.put(Level.FINER, org.apache.log4j.Level.TRACE);
        levelMap.put(Level.FINEST, org.apache.log4j.Level.TRACE);
        levelMap.put(Level.ALL, org.apache.log4j.Level.ALL);

    }

    public SyslogHandler() {
        syslogAppender = new SyslogAppender();
        PatternLayout patternLayout = new PatternLayout("WFA [%c] %m%n");
        syslogAppender.setLayout(patternLayout);
    }

    @Override
    public void publish(LogRecord record) {

        syslogAppender.append(new LoggingEvent(record.getSourceClassName(),
                org.apache.log4j.Logger.getLogger(record.getLoggerName()),
                levelMap.get(record.getLevel()),
                record.getMessage(),
                record.getThrown()));

    }

    @Override
    public void flush() {
    }

    @Override
    public void close() throws SecurityException {
        syslogAppender.close();
    }

    public void setName(String name) {
        this.syslogAppender.setName(name);
    }

    public void setSyslogHost(String logHost) {
        this.syslogAppender.setSyslogHost(logHost);
    }

    public void setThreshold(Priority threshold) {
        this.syslogAppender.setThreshold(threshold);
    }

    public static SyslogHandler getFromLogger(Logger logger) {
        for (Handler handler : logger.getHandlers()) {
            if (handler instanceof SyslogHandler) {
                return (SyslogHandler)handler;
            }
        }
        return null;
    }
}
